package org.itheima.googleplay.ui.fragment;

import java.util.List;

import org.itheima.googleplay.bean.CategoryBean;
import org.itheima.googleplay.http.CategoryProtocol;
import org.itheima.googleplay.ui.adapter.SuperBaseAdapter;
import org.itheima.googleplay.ui.fragment.LoadingPager.LoadedResult;
import org.itheima.googleplay.ui.holder.BaseHolder;
import org.itheima.googleplay.ui.holder.CategoryItemHolder;
import org.itheima.googleplay.ui.holder.CategoryTitleHolder;
import org.itheima.googleplay.ui.weiget.BaseListView;
import org.itheima.googleplay.utils.UIUtils;

import android.view.View;
import android.widget.AbsListView;

/**
 * @包名: org.itheima.googleplay.ui.fragment
 * @类名: CategoryFragment
 * @作者: 肖琦
 * @创建时间 : 2015-3-23 上午11:05:32
 * 
 * @描述: 分类页面
 * 
 * @SVN版本: $Rev: 17 $
 * @更新人: $Author: xq $
 * @更新时间: $Date: 2015-03-23 15:05:09 +0800 (星期一, 23 三月 2015) $
 * 
 * @更新描述:
 */
public class CategoryFragment extends BaseFragment
{
	private CategoryProtocol	mProtocol;
	private List<CategoryBean>	mListDatas;

	@Override
	protected View onSuccessView()
	{
		// 新建listView
		BaseListView listView = new BaseListView(UIUtils.getContext());

		// 设置Adpater --> list
		listView.setAdapter(new CategoryAdapter(listView, mListDatas));

		return listView;
	}

	@Override
	protected LoadedResult onLoadData()
	{
		// 新建协议
		mProtocol = new CategoryProtocol();

		try
		{
			// 加载数据
			mListDatas = mProtocol.loadData(0);

			// 数据检查
			return checkState(mListDatas);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return LoadedResult.ERROR;
		}
	}

	class CategoryAdapter extends SuperBaseAdapter<CategoryBean>
	{

		public CategoryAdapter(AbsListView listView, List<CategoryBean> datas) {
			super(listView, datas);
		}

		@Override
		protected BaseHolder<CategoryBean> getHolder(int position)
		{
			// 根据数据判断 该显示什么样的View
			CategoryBean bean = mDatas.get(position);

			if (bean.isTitle)
			{
				return new CategoryTitleHolder();
			}
			else
			{
				return new CategoryItemHolder();
			}
		}

		// 取消加载更多
		@Override
		protected boolean hasLoadMore()
		{
			return false;
		}

		@Override
		public int getViewTypeCount()
		{
			return super.getViewTypeCount() + 1;
		}

		@Override
		protected int getInnerItemViewType(int position)
		{
			CategoryBean bean = mDatas.get(position);
			if (bean.isTitle)
			{
				// 有titleholder
				return super.getInnerItemViewType(position);
			}
			else
			{
				// itemholder
				return super.getInnerItemViewType(position) + 1;
			}
		}
	}

}
